import comtypes.client
from string import Template
import tempfile
import time

def connect_to_rhino(tlb_path):
    # Connect to rhino and get rhinoscript object
    RhinoScriptModule = comtypes.client.GetModule(tlb_path)
    Rhino = comtypes.client.CreateObject("Rhino5.Application")
    Rhino.Visible = True
    rs = Rhino.GetScriptObject.QueryInterface(RhinoScriptModule.IRhinoScript)
    return rs



def run_grasshopper(gh_file, param_nodes, param_values, output_node):
    
    # VB script
    vb_script = Template("""
Sub Main()
  Dim GH : Set GH = Rhino.GetPlugInObject("Grasshopper")
  GH.OpenDocument "$GH_FILE"
$PARAMETERS
  GH.RunSolver True
  GH.BakeDataInObject "$OUT"
  GH.CloseAllDocuments
End Sub
Call Main()""")
    
    # Create parameter string
    parameters = "    "
    for  param_node, param_value in zip(param_nodes, param_values):
        parameters += '  GH.AssignDataToParameter "'+param_node+'" '+str(param_value)+'\n'
        
    # Write the script
    temp_dir = tempfile.gettempdir()
    print temp_dir
    vb_script_path = temp_dir + "/run_gh.rvb"
    f = open(vb_script_path, 'w')
    f.write(vb_script.substitute(GH_FILE=gh_file, PARAMETERS=parameters, OUT=output_node))
    f.close()
    
    # Run the script
    rs.Command("-LoadScript "+vb_script_path, False)
    

rs = connect_to_rhino(tlb_path=r"C:\Program Files\Rhinoceros 5 Evaluation\Plug-ins\RhinoScript.tlb")
#run_grasshopper("D:/Temp/test2.gh", ["R"], [4], "OUT")
#rs.DocumentModified(False)
#rs.Command("-Exit", False)
print rs
time.sleep(20)
rs.AddCurve([[54,3,0],[2,34,0],[23,45,0]])
time.sleep(5)
print("Done")